package com.kexio.file.controller;

import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.kexio.common.dto.Result;
import com.kexio.dynamic.feature.annotation.FeatureToggle;
import com.kexio.file.domain.FileInfo;
import com.kexio.file.dto.PreviewResult;
import com.kexio.file.service.FilePreviewService;
import com.kexio.file.service.FileService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 文件预览控制器
 * 
 * @author kexio
 */
@RestController
@RequestMapping("/api/files/preview")
@Tag(name = "文件预览", description = "文件预览相关API")
public class FilePreviewController {

    @Autowired
    private FilePreviewService filePreviewService;

    @Autowired
    private FileService fileService;

    /**
     * 预览文件
     */
    @Operation(summary = "预览文件", description = "生成文件预览内容")
    @FeatureToggle(value = "file_preview", description = "文件预览功能")
    @GetMapping("/{fileId}")
    public ResponseEntity<?> previewFile(
            @Parameter(description = "文件ID", required = true) @PathVariable Long fileId,
            @RequestParam Long userId) {
        
        try {
            // 获取文件信息
            FileInfo fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                return ResponseEntity.ok(Result.error("文件不存在"));
            }

            // 检查是否支持预览
            if (!filePreviewService.isPreviewable(fileInfo)) {
                return ResponseEntity.ok(Result.error("该文件类型不支持预览"));
            }

            // 获取文件流
            InputStream fileStream = fileService.downloadFile(fileId, userId);
            
            // 生成预览
            PreviewResult previewResult = filePreviewService.generatePreview(fileInfo, fileStream);
            
            // 根据预览类型返回不同的响应
            switch (previewResult.getPreviewType()) {
                case HTML:
                    return ResponseEntity.ok()
                        .contentType(MediaType.TEXT_HTML)
                        .body(previewResult.getContent());
                        
                case TEXT:
                    return ResponseEntity.ok()
                        .contentType(MediaType.TEXT_PLAIN)
                        .body(previewResult.getContent());
                        
                case IMAGE:
                    // 重定向到图片URL
                    return ResponseEntity.status(HttpStatus.FOUND)
                        .header(HttpHeaders.LOCATION, previewResult.getPreviewUrl())
                        .build();
                        
                case PDF:
                    return ResponseEntity.ok(Result.success(previewResult));
                    
                default:
                    return ResponseEntity.ok(Result.success(previewResult));
            }
            
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error("预览失败: " + e.getMessage()));
        }
    }

    /**
     * 获取文件缩略图
     */
    @Operation(summary = "获取缩略图", description = "生成文件缩略图")
    @GetMapping("/thumbnail/{fileId}")
    public ResponseEntity<byte[]> getThumbnail(
            @Parameter(description = "文件ID", required = true) @PathVariable Long fileId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "200") int width,
            @RequestParam(defaultValue = "150") int height) {
        
        try {
            // 获取文件信息
            FileInfo fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                return ResponseEntity.notFound().build();
            }

            // 获取文件流
            InputStream fileStream = fileService.downloadFile(fileId, userId);
            
            // 生成缩略图
            byte[] thumbnail = filePreviewService.generateThumbnail(fileInfo, fileStream, width, height);
            
            if (thumbnail == null) {
                return ResponseEntity.notFound().build();
            }
            
            return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(thumbnail);
                
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取PDF指定页面预览
     */
    @Operation(summary = "PDF页面预览", description = "获取PDF文档指定页面的预览图")
    @GetMapping("/pdf/{fileId}/page/{pageNumber}")
    public ResponseEntity<byte[]> getPdfPagePreview(
            @Parameter(description = "文件ID", required = true) @PathVariable Long fileId,
            @Parameter(description = "页码", required = true) @PathVariable int pageNumber,
            @RequestParam Long userId) {
        
        try {
            // 获取文件信息
            FileInfo fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null || !"pdf".equals(fileInfo.getFileExtension())) {
                return ResponseEntity.notFound().build();
            }

            // 获取文件流
            InputStream fileStream = fileService.downloadFile(fileId, userId);
            
            // 生成页面预览
            byte[] pagePreview = filePreviewService.generatePagePreview(fileInfo, fileStream, pageNumber);
            
            if (pagePreview == null) {
                return ResponseEntity.notFound().build();
            }
            
            return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(pagePreview);
                
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取PDF页数
     */
    @Operation(summary = "获取PDF页数", description = "获取PDF文档的总页数")
    @GetMapping("/pdf/{fileId}/pages")
    public ResponseEntity<Result<Integer>> getPdfPageCount(
            @Parameter(description = "文件ID", required = true) @PathVariable Long fileId,
            @RequestParam Long userId) {
        
        try {
            // 获取文件信息
            FileInfo fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null || !"pdf".equals(fileInfo.getFileExtension())) {
                return ResponseEntity.ok(Result.error("不是PDF文件"));
            }

            // 获取文件流
            InputStream fileStream = fileService.downloadFile(fileId, userId);
            
            // 获取页数
            int pageCount = filePreviewService.getDocumentPageCount(fileInfo, fileStream);
            
            return ResponseEntity.ok(Result.success(pageCount));
            
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error("获取页数失败: " + e.getMessage()));
        }
    }

    /**
     * 检查文件是否支持预览
     */
    @Operation(summary = "检查预览支持", description = "检查文件是否支持预览")
    @GetMapping("/check/{fileId}")
    public ResponseEntity<Result<Boolean>> checkPreviewSupport(
            @Parameter(description = "文件ID", required = true) @PathVariable Long fileId) {
        
        try {
            FileInfo fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                return ResponseEntity.ok(Result.error("文件不存在"));
            }
            
            boolean isPreviewable = filePreviewService.isPreviewable(fileInfo);
            return ResponseEntity.ok(Result.success(isPreviewable));
            
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error("检查失败: " + e.getMessage()));
        }
    }
}
